package com.blue.gateway.utils;
import com.blue.gateway.dto.Result;
import com.blue.gateway.dto.ResultWrapper;
import com.blue.gateway.enums.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RetryUtil {


    private static final byte MAX_RETRY_COUNT = 3;

    public static Result execute(RetryCode retryCode) {
        Result result = null;
        for (int retryCount = 1; retryCount <= MAX_RETRY_COUNT; retryCount++) {
            try {
                result = retryCode.execute();
            } catch (Exception e) {
                log.warn("execute code fail will retry. ", e);
            }
            if (result != null && result.isSuccess()) {
                return result;
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return ResultWrapper.fail(ResultCodeEnum.SYSTEM_ERROR);
            }
        }
        return result != null ? result : ResultWrapper.fail(ResultCodeEnum.SYSTEM_ERROR);
    }

    public interface RetryCode {
        Result execute();
    }

}
